package org.tgcloud.group.web.controller.manager;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.tgcloud.group.core.*;
import org.tgcloud.group.core.custom.Permissions;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.service.manager.HomeManageService;
import org.tgcloud.group.web.controller.dto.home.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: zhy
 * @create: 2023-09-26 14:54
 * @description: 首页相关接口
 */
@Api(tags = "首页相关接口")
@RestController
@RequestMapping("/manager/pc/user")
@EnableAutoConfiguration
public class HomeManageController extends ManageAPPBaseController{

    @Autowired
    private HomeManageService homeManageService;

    @ApiOperation(value = "首页1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/home1", method = RequestMethod.POST)
    public APPResultMessage doSendOrder(@ModelAttribute("session") Session session,
                                        @RequestParam Long startTime,
                                        @RequestParam Long endTime) throws Exception{
        return homeManageService.doSendOrder(startTime == null ? null : new Date(startTime), endTime == null ? null : new Date(endTime));
    }

    @ApiOperation(value = "首页数据-年份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getHomeYear", method = RequestMethod.POST)
    public APPResultMessage getHomeYear(@ModelAttribute("session") Session session,
                                    @RequestParam Long time){
        return homeManageService.getHomeYear(time == null ? null : new Date(time));
    }

    @ApiOperation(value = "首页数据-月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getHomeMonth", method = RequestMethod.POST)
    public APPResultMessage getHomeMonth(@ModelAttribute("session") Session session,
                                    @RequestParam Long time){
        return homeManageService.getHomeMonth(time == null ? null : new Date(time));
    }

    @ApiOperation(value = "首页数据-签单项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getHomeSignProject", method = RequestMethod.POST)
    public APPResultMessage getHomeSignProject(@ModelAttribute("session") Session session,
                                               @RequestParam(required = false) Long time,
                                               @RequestParam(required = false) Long endTime,
                                               @RequestParam(required = false) Long startArrivalTime,
                                               @RequestParam(required = false) Long endArrivalTime,
                                               @RequestParam(required = false) Integer pageNum,
                                               @RequestParam(required = false) Integer pageSize,
                                               @RequestParam(required = false) Integer useType,
                                               @RequestParam(required = false) String businessIds,
                                               @RequestParam(required = false) Integer areaId,
                                               @RequestParam(required = false) String invoiceCompany,
                                               @RequestParam(required = false) String projectName,
                                               @RequestParam(required = false) String brands,
                                               @RequestParam(required = false) String areaIds,
                                               @RequestParam(required = false) String statuses,
                                               @RequestParam(required = false) String arrivalProgressIds,
                                               @RequestParam(required = false) String invoiceCompanyIds,
                                               @RequestParam(required = false) String orderNo,
                                               @RequestParam(required = false) String cateIds,
                                               @RequestParam(required = false) String innerPriceSearches,
                                               @RequestParam(required = false) String actualValuePriceSearches,
                                               @RequestParam(required = false) String saleRealPriceSearches,
                                               @RequestParam(required = false) String estimatedCostSearches,
                                               @RequestParam(required = false) String actualCostSearches,
                                               @RequestParam(required = false) String arrivalRateSearches,
                                               @RequestParam(required = false) BigDecimal startProjectRateGross,
                                               @RequestParam(required = false) BigDecimal endProjectRateGross,
                                               @RequestParam(required = false) String estimatedSelfMediaCostSearches,
                                               @RequestParam(required = false) String estimatedExternalMediaCostSearches,
                                               @RequestParam(required = false) String actualSelfMediaCostSearches,
                                               @RequestParam(required = false) String actualExternalMediaCostSearches){
        return homeManageService.getHomeSignProject(time == null ? null : new Date(time),
                endTime == null ? null : new Date(endTime),
                startArrivalTime == null ? null : new Date(startArrivalTime),
                endArrivalTime == null ? null : new Date(endArrivalTime),
                pageNum, pageSize, useType,
                businessIds, areaId, invoiceCompany, projectName, brands,
                areaIds, statuses, arrivalProgressIds, invoiceCompanyIds,orderNo,cateIds,
                innerPriceSearches, actualValuePriceSearches, saleRealPriceSearches, estimatedCostSearches, actualCostSearches,
                arrivalRateSearches, startProjectRateGross, endProjectRateGross,
                estimatedSelfMediaCostSearches, estimatedExternalMediaCostSearches,
                actualSelfMediaCostSearches, actualExternalMediaCostSearches);
    }




    @ApiOperation(value = "首页商务数据-月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getBusinessHomeMonth", method = RequestMethod.POST)
    public APPResultMessage getBusinessHomeMonth(@ModelAttribute("session") Session session,
                                                @RequestParam Long time){
        return homeManageService.getBusinessMonthList2(time == null ? null : new Date(time));
    }


    @ApiOperation(value = "首页商务数据-月份--分组数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getChildrenList", method = RequestMethod.POST)
    public APPResultMessage getChildrenList(@ModelAttribute("session") Session session,
                                                 @RequestParam Long time,
                                                 @RequestParam Integer areaId
                                            ){
        return homeManageService.getChildrenList(time == null ? null : new Date(time),areaId);
    }




    @ApiOperation(value = "首页商务列表-月份")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getBusinessHomeMonthList", method = RequestMethod.POST)
    public APPResultMessage getBusinessHomeMonthList(@ModelAttribute("session") Session session,
                                                     @RequestParam Long time,
                                                     @RequestParam(required = false) Integer pageNum,
                                                     @RequestParam(required = false) Integer pageSize,
                                                     @RequestParam(required = false) String businessIds,
                                                     @RequestParam(required = false) String area,
                                                     @RequestParam(required = false) Integer targetId){
        return homeManageService.getBusinessHomeMonthList(time == null ? null : new Date(time), pageNum, pageSize, businessIds, area,targetId);
    }

    @ApiOperation(value = "首页商务列表-绩效统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getBusinessPerformanceList", method = RequestMethod.POST)
    public APPResultMessage getBusinessPerformanceList(@ModelAttribute("session") Session session,
                                                     @RequestParam Long arriveTime,
                                                     @RequestParam(required = false) Integer pageNum,
                                                     @RequestParam(required = false) Integer pageSize,
                                                     @RequestParam(required = false) String businessIds,
                                                     @RequestParam(required = false) String area,
                                                     @RequestParam(required = false) Integer targetId
    ){
        return homeManageService.getBusinessPerformanceList(arriveTime == null ? null : new Date(arriveTime), pageNum, pageSize, businessIds, area,targetId);
    }

    @ApiOperation(value = "首页商务列表-个人利润")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getTotalPersonProfitList", method = RequestMethod.POST)
    public APPResultMessage getTotalPersonProfitList(@ModelAttribute("session") Session session,
                                                     @RequestParam Long time,
                                                     @RequestParam(required = false) Integer pageNum,
                                                     @RequestParam(required = false) Integer pageSize,
                                                     @RequestParam(required = false) String businessIds,
                                                     @RequestParam(required = false) String area,
                                                     @RequestParam(required = false) Integer blindType){
        return homeManageService.getTotalPersonProfit(time == null ? null : new Date(time), pageNum, pageSize, businessIds, area,blindType);
    }


    /* 导出 */
    @ApiOperation(value = "导出首页签单项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportOrder")
    public void doExportOrder(HttpServletResponse response,
                              @RequestParam(required = false) Long time,
                              @RequestParam(required = false) Long endTime,
                              @RequestParam Integer useType,
                              @RequestParam(required = false) Long startArrivalTime,
                              @RequestParam(required = false) Long endArrivalTime,
                              @RequestParam(required = false) String businessIds,
                              @RequestParam(required = false) Integer areaId,
                              @RequestParam(required = false) String invoiceCompany,
                              @RequestParam(required = false) String projectName,
                              @RequestParam(required = false) String brands,
                              @RequestParam(required = false) String areaIds,
                              @RequestParam(required = false) String statuses,
                              @RequestParam(required = false) String arrivalProgressIds,
                              @RequestParam(required = false) String invoiceCompanyIds,
                              @RequestParam(required = false) String orderNo,
                              @RequestParam(required = false) String cateIds,
                              @RequestParam(required = false) String innerPriceSearches,
                              @RequestParam(required = false) String actualValuePriceSearches,
                              @RequestParam(required = false) String saleRealPriceSearches,
                              @RequestParam(required = false) String estimatedCostSearches,
                              @RequestParam(required = false) String actualCostSearches,
                              @RequestParam(required = false) String arrivalRateSearches,
                              @RequestParam(required = false) BigDecimal startProjectRateGross,
                              @RequestParam(required = false) BigDecimal endProjectRateGross,
                              @RequestParam(required = false) String estimatedSelfMediaCostSearches,
                              @RequestParam(required = false) String estimatedExternalMediaCostSearches,
                              @RequestParam(required = false) String actualSelfMediaCostSearches,
                              @RequestParam(required = false) String actualExternalMediaCostSearches) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = null;
        if (time != null && endTime != null){
            excelName = dateFormat.format(new Date(time)) + "已签单项目" + dateFormat1.format(new Date());


        } else if (startArrivalTime != null && endArrivalTime != null){
            excelName = dateFormat.format(new Date(startArrivalTime)) + "已签单项目" + dateFormat1.format(new Date());
            time = null;
            endTime = null;
        } else {
            excelName = dateFormat1.format(new Date()) + "已签单项目";
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        HomeProjectMsg msg = new HomeProjectMsg();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){
            field.setAccessible(true);
            String value = field.getAnnotation(ApiModelProperty.class).value();
            headers.add(value);
        }


        try {
            OutputStream out = response.getOutputStream();
            APPResultMessage successMessage = homeManageService.getHomeSignProject(time == null ? null : new Date(time),
                    endTime == null ? null : new Date(endTime),
                    startArrivalTime == null ? null : new Date(startArrivalTime),
                    endArrivalTime == null ? null : new Date(endArrivalTime),
                    null,null, useType,
                    businessIds, areaId, invoiceCompany, projectName, brands, areaIds, statuses,
                    arrivalProgressIds, invoiceCompanyIds,orderNo,cateIds, innerPriceSearches, actualValuePriceSearches,
                    saleRealPriceSearches, estimatedCostSearches, actualCostSearches, arrivalRateSearches,
                    startProjectRateGross, endProjectRateGross,
                    estimatedSelfMediaCostSearches, estimatedExternalMediaCostSearches,
                    actualSelfMediaCostSearches, actualExternalMediaCostSearches);
            getExportOrderListExcel(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getExportOrderListExcel(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(20);
        //生成一个样式，用来设置标题样式
        HSSFCellStyle style = workbook.createCellStyle();
        //设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        //生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        //把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式,用于设置内容样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 价格样式
        CellStyle priceCellStyle = workbook.createCellStyle();
        DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
        priceCellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字

        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        List list = message.getResult().getList();
        if (!BeanUtil.isNullList(list)) {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                int j = 0;
                HomeProjectMsg dto = (HomeProjectMsg) list.get(i);
                // 获取excel里对应的值
                Field[] declaredFields = dto.getClass().getDeclaredFields();
                for (Field field : declaredFields){
                    field.setAccessible(true);
                    Object o = field.get(dto);
                    HSSFCell cell = row.createCell(j++);
                    if (o == null){
                        cell.setCellValue("");
                    }else {
                        if (o instanceof Date){
                            Date date = new Date(((Date) o).getTime());
                            cell.setCellValue(DateUtil.getStrDate(date));
                        }else if (o instanceof BigDecimal){
                            cell.setCellStyle(priceCellStyle);
                            if (JSON.toJSONString(o).equals("0E-8")){
                                cell.setCellValue(0);
                            }else if (JSON.toJSONString(o).equals("0E-24")){
                                cell.setCellValue(0);
                            }else {
                                cell.setCellValue(((BigDecimal) o).doubleValue());
                            }
                        }else {
                            cell.setCellValue(o.toString());
                        }

                        if (field.getName().equals("status") && StringUtil.isNotBlank(o.toString())){
                            String statusName = o.toString().equals("1") ? "创建中" : o.toString().equals("2") ? "核价中" :
                                            o.toString().equals("3") ? "跟进中" : o.toString().equals("4") ? "已签单" :
                                                    o.toString().equals("5") ? "执行完" : "已黄单";
                            cell.setCellValue(statusName);
                        }
                    }
                }

            }
        }

        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /* 导出 */
    @ApiOperation(value = "导出首页商务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportBusiness")
    public void doExportBusiness(HttpServletResponse response,
                                 @RequestParam Long time,
                                 @RequestParam(required = false) String businessIds,
                                 @RequestParam(required = false) String area,
                                 @RequestParam(required = false) Integer targetId
                                 ) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = dateFormat.format(new Date(time)) + "商务" + dateFormat1.format(new Date());
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        HomeBusinessListDTO msg = new HomeBusinessListDTO();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){

            field.setAccessible(true);
            if (!field.isAnnotationPresent(ApiModelProperty.class)) {
                continue;
            }
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            if (!apiModelProperty.hidden()) { // 检查hidden属性是否为true
                String value = apiModelProperty.value();
                headers.add(value);
            }
        }
        try {
            OutputStream out = response.getOutputStream();
            APPResultMessage successMessage = homeManageService.getBusinessHomeMonthList(time == null ? null : new Date(time), null, null, businessIds, area,targetId);
            getExportBusinessListExcel(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* 导出 */
    @ApiOperation(value = "导出首页商务区域统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportAreaBusiness")
    public void doExportAreaBusiness(HttpServletResponse response, @RequestParam Long time) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = dateFormat.format(new Date(time)) + "商务区域统计" + dateFormat1.format(new Date());
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        HomeBusinessList2DTO msg = new HomeBusinessList2DTO();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){
            field.setAccessible(true);
            String value = field.getAnnotation(ApiModelProperty.class).value();
            headers.add(value);
        }
        try {
            OutputStream out = response.getOutputStream();
            APPResultMessage successMessage = homeManageService.getBusinessMonthList2(time == null ? null : new Date(time));
            getExportAreaBusinessExcel(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getExportAreaBusinessExcel(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(20);
        //生成一个样式，用来设置标题样式
        HSSFCellStyle style = workbook.createCellStyle();
        //设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        //生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        //把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式,用于设置内容样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 价格样式
        CellStyle priceCellStyle = workbook.createCellStyle();
        DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
        priceCellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字

        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        List list = message.getResult().getList();
        if (!BeanUtil.isNullList(list)) {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                int j = 0;
                HomeBusinessList2DTO dto = (HomeBusinessList2DTO) list.get(i);
                // 获取excel里对应的值
                Field[] declaredFields = dto.getClass().getDeclaredFields();
                for (Field field : declaredFields){
                    field.setAccessible(true);
                    Object o = field.get(dto);
                    HSSFCell cell = row.createCell(j++);
                    if (o == null){
                        cell.setCellValue("");
                    }else {
                        if (o instanceof Date){
                            Date date = new Date(((Date) o).getTime());
                            cell.setCellValue(DateUtil.getStrDate(date));
                        }else if (o instanceof BigDecimal){
                            cell.setCellStyle(priceCellStyle);
                            if (JSON.toJSONString(o).equals("0E-8")){
                                cell.setCellValue(0);
                            }else if (JSON.toJSONString(o).equals("0E-24")){
                                cell.setCellValue(0);
                            }else {
                                cell.setCellValue(((BigDecimal) o).doubleValue());
                            }
                        }else {
                            cell.setCellValue(o.toString());
                        }

//                        if (field.getName().equals("status") && StringUtil.isNotBlank(o.toString())){
//                            String statusName = o.toString().equals("1") ? "创建中" : o.toString().equals("2") ? "核价中" :
//                                    o.toString().equals("3") ? "跟进中" : o.toString().equals("4") ? "已签单" :
//                                            o.toString().equals("5") ? "执行完" : "已黄单";
//                            cell.setCellValue(statusName);
//                        }
                    }
                }

            }
        }

        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





    public static void getExportBusinessListExcel(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(20);
        //生成一个样式，用来设置标题样式
        HSSFCellStyle style = workbook.createCellStyle();
        //设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        //生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        //把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式,用于设置内容样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);
        // 价格样式
        CellStyle priceCellStyle = workbook.createCellStyle();
        DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
        priceCellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字

        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }
        List list = message.getResult().getList();
        if (!BeanUtil.isNullList(list)) {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                int j = 0;
                HomeBusinessListDTO dto = (HomeBusinessListDTO) list.get(i);
                // 获取excel里对应的值
                Field[] declaredFields = dto.getClass().getDeclaredFields();
                for (Field field : declaredFields){
                    field.setAccessible(true);
                    ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                    if (annotation != null && annotation.hidden()) { // 检查字段是否隐藏
                        continue; // 跳过隐藏字段
                    }
                    Object o = field.get(dto);
                    HSSFCell cell = row.createCell(j++);

                    if (o == null){
                        cell.setCellValue("");
                    }else {
                        if (o instanceof Date){
                            Date date = new Date(((Date) o).getTime());
                            cell.setCellValue(DateUtil.getStrDate(date));
                        }else if (o instanceof BigDecimal){

                            cell.setCellStyle(priceCellStyle);
                            if (JSON.toJSONString(o).equals("0E-8")){
                                cell.setCellValue(0);
                            }else if (JSON.toJSONString(o).equals("0E-24")){
                                cell.setCellValue(0);
                            }else {
                                cell.setCellValue(((BigDecimal) o).doubleValue());
                            }
                        }else {
                            cell.setCellValue(o.toString());
                        }
                        if (field.getName().equals("rateLevel") && StringUtil.isNotBlank(o.toString())){
                            BigDecimal a = (BigDecimal) o;
                            String levelName = "";
                            if (a.compareTo(new BigDecimal(5)) >= 0){
                                levelName = "优秀";
                            }else if (a.compareTo(new BigDecimal(5)) < 0 && a.compareTo(new BigDecimal(3)) >= 0){
                                levelName = "良好";
                            }else if (a.compareTo(new BigDecimal(3)) < 0 && a.compareTo(new BigDecimal(1)) >= 0){
                                levelName = "差";
                            }else if (a.compareTo(new BigDecimal(1)) < 0){
                                levelName = "极差";
                            }
                            cell.setCellValue(levelName);
                        }
                    }
                }

            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "导出首页商务区域个人利润统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportTotalPersonProfit")
    public void doExportAreaBusiness(HttpServletResponse response,
                                     @RequestParam Long time,
                                     @RequestParam(required = false) Integer pageNum,
                                     @RequestParam(required = false) Integer pageSize,
                                     @RequestParam(required = false) String businessIds,
                                     @RequestParam(required = false) String area,
                                     @RequestParam(required = false) Integer blindType ) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = "";
        if (blindType == 1){
            excelName = dateFormat.format(new Date(time)) + "商务个人利润统计" + dateFormat1.format(new Date());
        } else {
            excelName = dateFormat.format(new Date(time)) + "商务个人去盲盒利润统计" + dateFormat1.format(new Date());
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        TotalPersonListDTO msg = new TotalPersonListDTO();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){
            field.setAccessible(true);
            String value = field.getAnnotation(ApiModelProperty.class).value();
            headers.add(value);
        }
        try {
            OutputStream out = response.getOutputStream();
            APPResultMessage successMessage = homeManageService.getTotalPersonProfit(time == null ? null : new Date(time), pageNum, pageSize, businessIds, area,blindType);
            getExportTotalPersonProfit(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getExportTotalPersonProfit(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        //设置表格默认列宽度为15个字符
        sheet.setDefaultColumnWidth(20);
        //生成一个样式，用来设置标题样式
        HSSFCellStyle style = workbook.createCellStyle();
        //设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        //生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        //把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式,用于设置内容样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 价格样式
        CellStyle priceCellStyle = workbook.createCellStyle();
        DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
        priceCellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字

        //产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }

        List list = message.getResult().getList();
        if (!BeanUtil.isNullList(list)) {
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                int j = 0;
                TotalPersonListDTO dto = (TotalPersonListDTO) list.get(i);
                // 获取excel里对应的值
                Field[] declaredFields = dto.getClass().getDeclaredFields();
                for (Field field : declaredFields){
                    field.setAccessible(true);
                    Object o = field.get(dto);
                    HSSFCell cell = row.createCell(j++);
                    if (o == null){
                        cell.setCellValue("");
                    }else {
                        if (o instanceof Date){
                            Date date = new Date(((Date) o).getTime());
                            cell.setCellValue(DateUtil.getStrDate(date));
                        }else if (o instanceof BigDecimal){
                            cell.setCellStyle(priceCellStyle);
                            if (JSON.toJSONString(o).equals("0E-8")){
                                cell.setCellValue(0);
                            }else if (JSON.toJSONString(o).equals("0E-24")){
                                cell.setCellValue(0);
                            }else {
                                cell.setCellValue(((BigDecimal) o).doubleValue());
                            }
                        }else {
                            cell.setCellValue(o.toString());
                        }

//                        if (field.getName().equals("status") && StringUtil.isNotBlank(o.toString())){
//                            String statusName = o.toString().equals("1") ? "创建中" : o.toString().equals("2") ? "核价中" :
//                                    o.toString().equals("3") ? "跟进中" : o.toString().equals("4") ? "已签单" :
//                                            o.toString().equals("5") ? "执行完" : "已黄单";
//                            cell.setCellValue(statusName);
//                        }
                    }
                }

            }
        }

        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "导出首页商务绩效")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @PostMapping(value = "/doExportPerformanceList")
    public void doExportPerformanceList(HttpServletResponse response,
                                        @RequestParam Long arriveTime,
                                        @RequestParam(required = false) Integer pageNum,
                                        @RequestParam(required = false) Integer pageSize,
                                        @RequestParam(required = false) String businessIds,
                                        @RequestParam(required = false) String area,
                                        @RequestParam(required = false) Integer targetId ) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmm");
        String excelName = dateFormat.format(new Date(arriveTime)) + "商务绩效" + dateFormat1.format(new Date());
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8") + ".xls");
        response.addHeader("filename", URLEncoder.encode(excelName, "UTF-8"));

        // 获取excel显示第一行的字段名
        List<String> headers = Lists.newArrayList();
        HomeBusinessPerformanceListDTO msg = new HomeBusinessPerformanceListDTO();
        Field[] declaredFields = msg.getClass().getDeclaredFields();
        for (Field field : declaredFields){
            field.setAccessible(true);
            if (!field.isAnnotationPresent(ApiModelProperty.class)) {
                continue;
            }
            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
            if (!apiModelProperty.hidden()) { // 检查hidden属性是否为true
                String value = apiModelProperty.value();
                headers.add(value);
            }
        }

        try {
            OutputStream out = response.getOutputStream();

            APPResultMessage successMessage = homeManageService.getBusinessPerformanceList(arriveTime == null ? null : new Date(arriveTime), null, null, businessIds, area,targetId);
            getExportPerformanceExcel(excelName, headers, successMessage, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getExportPerformanceExcel(String title, List<String> headers, APPResultMessage message, OutputStream out) throws Exception{
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            //设置表格默认列宽度为15个字符
            sheet.setDefaultColumnWidth(20);
            //生成一个样式，用来设置标题样式
            HSSFCellStyle style = workbook.createCellStyle();
            //设置这些样式
            style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
            //生成一个字体
            HSSFFont font = workbook.createFont();
            font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
            //把字体应用到当前的样式
            style.setFont(font);
            // 生成并设置另一个样式,用于设置内容样式
            HSSFCellStyle style2 = workbook.createCellStyle();
            style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
            // 生成另一个字体
            HSSFFont font2 = workbook.createFont();
            // 把字体应用到当前的样式
            style2.setFont(font2);

            // 价格样式
            CellStyle priceCellStyle = workbook.createCellStyle();
            DataFormat dataFormat = workbook.createDataFormat();  //创建一个单元格数据格式
            priceCellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));  //设置数据格式为数字

            //产生表格标题行
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < headers.size(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                HSSFRichTextString text = new HSSFRichTextString(headers.get(i));
                cell.setCellValue(text);
            }

            List list = message.getResult().getList();
            if (!BeanUtil.isNullList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow(i + 1);
                    int j = 0;
                    HomeBusinessPerformanceListDTO dto = (HomeBusinessPerformanceListDTO) list.get(i);
                    // 获取excel里对应的值
                    Field[] declaredFields = dto.getClass().getDeclaredFields();
                    for (Field field : declaredFields){
                        field.setAccessible(true);
                        ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                        if (annotation != null && annotation.hidden()) { // 检查字段是否隐藏
                            continue; // 跳过隐藏字段
                        }
                        Object o = field.get(dto);
                        HSSFCell cell = row.createCell(j++);
                        if (o == null){
                            cell.setCellValue("");
                        }else {
                            if (o instanceof Date){
                                Date date = new Date(((Date) o).getTime());
                                cell.setCellValue(DateUtil.getStrDate(date));
                            }else if (o instanceof BigDecimal){
                                cell.setCellStyle(priceCellStyle);
                                if (JSON.toJSONString(o).equals("0E-8")){
                                    cell.setCellValue(0);
                                }else if (JSON.toJSONString(o).equals("0E-24")){
                                    cell.setCellValue(0);
                                }else {
                                    cell.setCellValue(((BigDecimal) o).doubleValue());
                                }
                            }else {
                                cell.setCellValue(o.toString());
                            }

                    }

                }
            }

            try {
                workbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    @Permissions("project:editSomePrice")
    @ApiOperation(value = "首页签单列表-修改签单的部分数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doEditSomeProjectPrice", method = RequestMethod.POST)
    public APPResultMessage doEditSomeProjectPrice(@ModelAttribute("session") Session session,
                                                   @RequestParam Integer projectId,
                                                   @RequestParam(required = false) BigDecimal innerPrice,
                                                   @RequestParam(required = false) BigDecimal actualValuePrice,
                                                   @RequestParam(required = false) BigDecimal saleRealPrice,
                                                   @RequestParam(required = false) BigDecimal estimatedSelfMediaCost,
                                                   @RequestParam(required = false) BigDecimal estimatedExternalMediaCost,
                                                   @RequestParam(required = false) BigDecimal actualSelfMediaCost,
                                                   @RequestParam(required = false) BigDecimal actualExternalMediaCost){
        return homeManageService.doEditSomeProjectPrice(projectId, innerPrice, actualValuePrice, saleRealPrice,
                estimatedSelfMediaCost, estimatedExternalMediaCost,
                actualSelfMediaCost, actualExternalMediaCost);
    }


}
